<?php
require_once "handler.class.php";

class qForHandler extends qHandler
{
    function __construct()
    {
        $this->iscloseable = true;
        $this->parsechildren = false;
    }
    
    public function Parse($tag, $body)
    {
		$parameter = mb_substr($tag, 5, -1);
		$preg = '/(.*); (.*); (.*)/';
		
		$values = qTemplateParser::Values();
		
		preg_match($preg, $parameter, $array);
		
		if ($array[1] != '')
		{
			$preg = '/\$([a-zA-Z0-9\.]+) *= *(.+)/';
			if (preg_match($preg, $array[1], $array2) == 0)
			{
			    return array(false, "qForHandler Error: first part of tag isn't empty and there is no assignation!<br />{$tag}{$body}{endfor}");
			}

		    $preg = '/\$([a-zA-Z0-9\.]+)/';
		    preg_match_all($preg, $array2[2], $first);
		    
		    foreach ($first as $elem)
		    {
				if (isset($values[$elem[1]]))
				{
			    	$array[1] = str_replace($elem[0], $values[$elem[1]], $array[1]);
				}
		    }
		    
		    eval($array[1].';');
		    qTemplateParser::AddValue($array2[1], ${$array2[1]});
		}
		
		//Dwa poni�sze znikn� jak dopisz� {break} i {continue} do {for...} i {foreach...} oraz {set...} <- TODO!
		if ($array[2] == '')
		{
		    return array(false, "qForHandler Error: second part of tag is empty!<br />{$tag}{$body}{endfor}");
		}
		
		if ($array[3] == '')
		{
		    return array(false, "qForHandler Error: third part of tag is empty!<br />{$tag}{$body}{endfor}");
		}
		
		$newbody = '';
		while (true)
		{
		    eval('$result = '.$array[2].';');
		    
		    if (!$result)
		    {
		        break;
		    }
		    
		    
		    
		    $newbody .= qTemplateParser::Parse($body);
		}
		
		return array(true, $newbody);
    }
}